// generateComponent.js`
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const defaultTemplate = require('./template')
const resolve = (project, ...file) => path.resolve(project, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
const generateFile = (path, data) => {
  if (fs.existsSync(path)) {
    errorLog(`${path}文件已存在`)
    return
  }
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', err => {
      if (err) {
        errorLog(err.message)
        reject(err)
      } else {
        resolve(true)
      }
    })
  })
}
// 默认路径
const defaultPath = '/admin/src/mock/modules'
// 创建组件
function createMock(option, tableData, inputName) {
  return new Promise(async (resFn) => {
    let MockTemplate
    let componentName = ''
    let routePath = ''
    const userProjectDirectory = process.cwd() + defaultPath
    MockTemplate = defaultTemplate.MockTemplate
    if (option.path.includes('/')) {
      routePath = option.path.split('/')[0]
    } else {
      routePath = option.path
    }
    const componentVueName = resolve(userProjectDirectory, routePath)
    const componentDirectory = path.dirname(componentVueName)
    const hasComponentExists = fs.existsSync(componentVueName)
    if (hasComponentExists) {
      errorLog(`${option.path}已存在，请重新输入`)
      return
    } else {
      log(`生成目录 ${componentDirectory}`)
      await dotExistDirectoryCreate(componentDirectory)
    }
    try {
      if (inputName.includes('/')) {
        const inputArr = inputName.split('/')
        componentName = inputArr[inputArr.length - 1]
      } else {
        componentName = option.path
      }
      let columns = ''
      for (const field in tableData[0]) {
        columns += `${field}: 'test',`
      }

      columns = columns.substring(0, columns.length - 1)
      log(`生成 mock 文件 ${componentVueName}`)
      await generateFile(`${componentVueName}.js`, MockTemplate(componentName, columns))
      successLog('生成 mock 文件生成成功')
      resFn()
    } catch (e) {
      resFn()
      errorLog(e.message)
    }
  })
}
function dotExistDirectoryCreate(directory) {
  return new Promise((resolve) => {
    mkdirs(directory, () => {
      resolve(true)
    })
  })
}

// 递归创建目录
function mkdirs(directory, callback) {
  var exists = fs.existsSync(directory)
  if (exists) {
    callback()
  } else {
    mkdirs(path.dirname(directory), () => {
      fs.mkdirSync(directory)
      callback()
    })
  }
}
module.exports = { createMock }
